package com.rem.concurrency.juc.my13Single;

import java.lang.reflect.Constructor;

/**
 * DCL 懒汉式
 * 反射 创建多个对象
 *
 * @author Rem
 * @date 2021-03-10
 */

public class LazyMan3 {

    /**
     * volatile 避免指定重排
     */
    private volatile static LazyMan3 lazyMan;

    private LazyMan3() {
        System.out.println(Thread.currentThread().getName() + "ok");
    }


    /**
     * 双层检测的锁模式 DCL懒汉式
     *
     * @return
     */
    public static LazyMan3 getLazyMan() {
        //加锁操作
        if (lazyMan == null) {
            //加锁
            synchronized (LazyMan3.class) {
                if (lazyMan == null) {
                    //不是一个原子性的操作
                    lazyMan = new LazyMan3();
                }
            }
        }
        return lazyMan;
    }

    public static void main(String[] args) throws Exception {
        Class<LazyMan3> lazyMan3Class = LazyMan3.class;
        Constructor<LazyMan3> declaredConstructor = lazyMan3Class.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);

        LazyMan3 lazyManA = declaredConstructor.newInstance();
        LazyMan3 lazyManB = declaredConstructor.newInstance();

        System.out.println(lazyManA);
        System.out.println(lazyManB);
        //false  创建了两个对象
        System.out.println(lazyManA == lazyManB);
    }
}